<template>
	<view class="my-container">
		<view class="my-forms">
			<view class="my-list" style="padding: 0rpx 40rpx 0rpx;">
				<view class="opt_1_view">
					<view class="item" v-for="(item,index) in opt_1_list" :key="index" :class="opt_current_1==index?'active':''"
						@tap="opt_item_1_tap(index)">
						<view class="text">{{item.title}}</view>
					</view>
				</view>
				<view class="cell-column" v-if="opt_current_1 == 0">
					<view class="imageList">
						<view class="imgItem" v-for="(item,index) in fileUrlList" :key="index">
							<image class="image" :src="item.attaPath"></image>
							<image class="deleteImg" :src="`${img_baseUrl}/statics/std/static/delete.png`" @click="deleteImg(item)"></image>
						</view>
						<view v-if="fileUrlList.length < 9" class="image" @click="handleUploadImg">
							<image :src="`${img_baseUrl}/statics/std/static/youji.png`"></image>
							<text>
								上传封面
							</text>
						</view>
					</view>
					<view class="cell-text">
						第一张照片会自动成为封面
					</view>
				</view>
				<view class="cell-column" style="margin-bottom: 82rpx;" v-else>
					<view class="imageList">
						<view class="imgItem" v-for="(item,index) in videoUrlList" :key="index">
							<video class="image" id="myVideo" loop :show-center-play-btn="false" object-fit="fill" :controls="false"
								:src="img_baseUrl + item.attaPath" @click="pauseVideo()"></video>
							<image class="deleteImg" :src="`${img_baseUrl}/statics/std/static/delete.png`" @click="deleteVideo(item)"></image>
							<image class="bofangImg" :src="`${img_baseUrl}/statics/std/static/bofang.png`" mode="" @click="palyVideo(item)" v-if="palyShow">
							</image>
						</view>
						<view v-if="videoUrlList.length < 1" class="image" @click="handleUploadVideo">
							<image :src="`${img_baseUrl}/statics/std/static/youji.png`"></image>
							<text>
								上传视频
							</text>
						</view>
					</view>
				</view>
				<view class="cell-option" v-if="opt_current_1 == 0">
					<input class="input" v-model="sForm.title" placeholder="填写标题" />
				</view>
				<view class="cell-option" v-else>
					<input class="input" v-model="sForm.title" placeholder="输入视频介绍" />
				</view>
				<view class="container" v-if="opt_current_1 == 0">
					<div class='toolbar' @tap="format">
						<div :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold"></div>
						<div :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic"></div>
						<div :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian"
							data-name="underline"></div>
						<div :class="formats.header === 2 ? 'ql-active' : ''" class="iconfont icon-format-header-2"
							data-name="header" :data-value="2"></div>
						<div :class="formats.align === 'left' ? 'ql-active' : ''" class="iconfont icon-zuoduiqi" data-name="align"
							data-value="left"></div>
						<div :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi"
							data-name="align" data-value="center"></div>
						<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi" data-name="align"
							data-value="right"></view>
						<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie"
							data-name="list" data-value="bullet"></view>
						<div class="iconfont icon-charutupian" @tap="insertImage"></div>
						<!-- <view class="iconfont icon-undo" @tap="undo"></view>
						<view class="iconfont icon-redo" @tap="redo"></view>
						<div class="iconfont icon-shanchu" @tap="clear"></div> -->
					</div>
					<editor id="editor" class="ql-container" placeholder="请输入游记内容" @ready="onEditorReady"
						@statuschange="onStatusChange"></editor>
				</view>
			</view>
			<div class="space"></div>
			<view class="list">
				<view class="teacher_item" @tap="goTo()">
					<view class="list_left">
						<image :src="`${img_baseUrl}/statics/std/static/introduction-detail-position-location.png`"></image>
					</view>
					<view class="list_center">
						<view class="list_name">
							{{sForm.addr}}
						</view>
					</view>
					<view class="list_right">
						<image :src="`${img_baseUrl}/statics/std/static/go.png`" mode=""></image>
					</view>
				</view>
			</view>
			<div class="space"></div>
			<view class="classification">
				<view class="class_title">
					分类
				</view>
				<view class="class_list">
					<view class="item" v-for="(item,index) in class_list" :key="index"
						:class="class_current==index?'active_class':''" @tap="class_tap(item,index)">
						<view class="text">{{item.typeName}}</view>
					</view>
				</view>

			</view>
		</view>
		<view class="my-footer" :style="{bottom: GET_SAFEAREA_BOTTOM+'px'}">
			<button class="text" :loading="isSubmitting" :disabled="isSubmitting" @click="submitFun">提交</button>
		</view>
	</view>
</template>
<script>
	// import Editor from 'vue2-editor';
	// import 'vue2-editor/dist/vue2-editor.css'
	import {
		requestGet
	} from '@/utils/request.js'
	import requestPost from '@/utils/request.js';
	import {
		mapGetters
	} from 'vuex'
	import store, {
		GET_SAFEAREA_BOTTOM
	} from '../../store/index.js';
	import {throttle} from '@/utils/index.js'
  var amapFile = require('@/utils/amap-wx.130.js')
	export default {
		components: {
			// Editor,
		},
		data() {
			return {
				palyShow: true,
				img_baseUrl: process.env.VUE_APP_BASEURL_IMG_API,
				formats: {},
				content: '', // 存储编辑器内容
				class_current: 0,
				class_list: [],
				selectType: null,
				fileUrlList: [],
				videoUrlList: [],
				sForm: {
					title: null,
					addr: "",
					type: "", //类别（0文章/1视频）
					typeId: "", //游记分类id
					attachIds: "",
				},
				opt_1_list: [{
						title: "发布游记",
						id: 1
					},
					{
						title: "发短视频",
						id: 2
					},
				],
				opt_current_1: 0,
				travelsData: [],
        position: null,
        isSubmitting: false
			};
		},
		computed: {
			...mapGetters([GET_SAFEAREA_BOTTOM])
		},
		mounted() {
			this.getTravels()
			console.log('安全区距离', this.GET_SAFEAREA_BOTTOM);
      this.getCurrentLocation();
		},
		methods: {
      // 获取当前经纬度
      getCurrentLocation() {
      	let that = this
      	var myAmapFun = new amapFile.AMapWX({
      		key: 'df436f05cea4704b8ceb44a890104987'
      	});
        console.log('getRegeo===========')
        wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userLocation']) {
                    //如果授权结果为true，则获取相关信息
					myAmapFun.getRegeo({
					    success: function (data) {
					        that.sForm.addr =  data[0].name;
					        that.position = {
					          name: data[0].name,
					          desc: data[0].desc,
					          latitude: data[0].latitude,
					          longitude: data[0].longitude
					        }
					    },
					    fail: function (info) {
					        console.log('getRegeo===========fail',info)
					    }
					})
                } else {
                    //如果授权结果为false，执行授权操作
                    wx.authorize({
                        scope: 'scope.userLocation',
                        success: function (res) {
							myAmapFun.getRegeo({
							    success: function (data) {
							        that.sForm.addr =  data[0].name;
							        that.position = {
							          name: data[0].name,
							          desc: data[0].desc,
							          latitude: data[0].latitude,
							          longitude: data[0].longitude
							        }
							    },
							    fail: function (info) {
							        console.log('getRegeo===========fail',info)
							    }
							})
                        },
                        fail: function () { //如果用户点击拒绝，以后的每次点击授权每次都都会直接进入此回调
                            
                        }
                    })
                }
            }
        })
      },
			//点击播放视频
			palyVideo(item) {
				let videoContext = uni.createVideoContext('myVideo', this);
				videoContext.play() //开始播放
				this.palyShow = false
			},
			pauseVideo() {
				let videoContext = uni.createVideoContext('myVideo', this);
				videoContext.pause() //开始播放
				this.palyShow = true
			},
			onEditorReady() {
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
				}).exec()
				console.log("666666", this.editorCtx)
			},
			//撤销、重做这些不需要可以不写
			undo() {
				this.editorCtx.undo()
			},

			redo() {
				this.editorCtx.redo()
			},

			format(e) {
				let {
					name,
					value
				} = e.target.dataset
				if (!name) return
				this.editorCtx.format(name, value)
			},
			insertImage() {
				var that = this;
				uni.chooseImage({
          count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success(res) {
						const tempFilePaths = res.tempFilePaths;
						uni.uploadFile({
							url: process.env.VUE_APP_BASEURL_API + "/file/uploadAttaData", //域名+上传文件的请求接口 (根据你实际的接口来)       
							header: {
								'Authorization': "Bearer " + uni.getStorageSync('X-Token')
							},
							filePath: tempFilePaths[0],
							name: 'file',
							success(res) {
								var data = JSON.parse(res.data)
								that.editorCtx.insertImage({
									width: '100%', //设置宽度为100%防止宽度溢出手机屏幕
									height: 'auto',
									src: process.env.VUE_APP_BASEURL_IMG_API + data.data.attaPath,
									alt: '图像',
									success: function() {
										console.log('insert image success')
									}
								})
								console.log(that.editorCtx)
							}
						})
					}
				})
			},
			clear() {
				this.editorCtx.clear({
					success: function(res) {
						console.log("clear success")
					}
				})
			},
			onStatusChange(e) {
				const formats = e.detail
				this.formats = formats
			},
			// 获取游记分类列表
			getTravels() {
				requestGet("/applet/notes/type/list", {}, "/baseplatform")
					.then((res) => {
						if (res.code === 200) {
							this.class_list = res.data || [];
							this.sForm.typeId = res.data[0].typeId
						}
					})
					.catch((err) => console.log("错误了", err));
			},
			// 切换类型
			opt_item_1_tap(index) {
				this.opt_current_1 = index;
        this.fileUrlList = [];
			},
			//地址
			goTo() {
				console.log("8888")
				uni.chooseLocation({
					success: (res) => {
						this.sForm.addr = res.name
					},
					cancel: function() { //不执行
						console.log("取消")
					},
					fail: function(err) {
						console.log('取消按钮', err)
					}
				});
			},
			//切换分类
			class_tap(item, index) {
				this.class_current = index
				this.sForm.typeId = item.typeId
			},
			//input内容
			handleInput(e) {
				// this.sForm.suggestContent = e.detail.value;
			},
			// 点击上传图片操作
			handleUploadImg() {
				this.uploadImg().then(res => {
					const urlList = this.fileUrlList;
					urlList.push(res);
					this.fileUrlList = urlList;
				})
			},
			//删除图片
			deleteImg(src) {
				const imgArr = this.fileUrlList.filter(i => i != src);
				this.fileUrlList = imgArr;
			},
			//提交
			submitFun: throttle(function() {
				console.log('节流进来了')
        if(this.isSubmitting) return;
				var that = this;
				if (this.opt_current_1 == 0) {
					if (!this.fileUrlList.length > 0) {
						uni.showToast({
							title: '请上传图片！',
							icon: 'none'
						});
						return
					}
					if (!this.sForm.title || this.sForm.title == '') {
						uni.showToast({
							title: '请输入标题！',
							icon: 'none'
						});
						return
					}
					if (!this.sForm.addr || this.sForm.addr == '') {
						uni.showToast({
							title: '请选择地址！',
							icon: 'none'
						});
						return
					}

					that.editorCtx.getContents({
						success: function(data) {
							console.log("kkkkk", data)
							var ids = []
							if (that.fileUrlList.length > 0) {
								ids = that.fileUrlList.map((item) => {
									return item.attaId
								})
							}
							that.sForm.attachIds = ids.join(',')
							// this.sForm.content = this.content;
							that.sForm.type = that.opt_current_1.toString();
							that.sForm.content = data.html;
							const params = {
								...that.sForm
							};
							console.log('/suggestion/add======params', params)
							requestPost('/applet/notes', params, '/baseplatform').then(res => {
								if (res.code === 200) {
									uni.showToast({
										title: '操作成功！'
									});
									uni.navigateBack();
								}
							})
						},
						fail: function (err) {
							uni.showToast({
								title: err,
								icon: 'none'
							});
						}
					})
				} else {
					if (!this.videoUrlList.length > 0) {
						uni.showToast({
							title: '请上传视频！',
							icon: 'none'
						});
						return
					}
					if (!this.sForm.title || this.sForm.title == '') {
						uni.showToast({
							title: '请输入视频介绍！',
							icon: 'none'
						});
						return
					}
					if (!this.sForm.addr || this.sForm.addr == '') {
						uni.showToast({
							title: '请选择地址！',
							icon: 'none'
						});
						return
					}
					var ids = []
					if (this.videoUrlList.length > 0) {
						ids = this.videoUrlList.map((item) => {
							return item.attaId
						})
					}
					this.sForm.attachIds = ids.join(',')
					this.sForm.type = this.opt_current_1.toString();
					const params = {
						...this.sForm,
            latitude: this.position.latitude,
            longitude: this.position.longitude,
					};
					console.log('/applet/notes======params', params)
          this.isSubmitting = true;
					requestPost('/applet/notes', params, '/baseplatform').then(res => {
            this.isSubmitting = false;
						if (res.code === 200) {
							uni.showToast({
								title: '操作成功！'
							});
							uni.navigateBack();
						}
					})
				}
			}, 500),
			// 上传方法
			uploadImg() {
        const that = this;
				return new Promise((resolve, reject) => {
					uni.chooseImage({
						count: 10 - that.fileUrlList.length,
						sourceType: ['album', 'camera'],
						success(res) {
							const tempFilePaths = res.tempFilePaths;
							res.tempFilePaths.map(item => {
							  wx.uploadFile({
							    url: process.env.VUE_APP_BASEURL_API + "/file/uploadAttaData",
							    filePath: item,
							    header: {
							      Authorization: "Bearer " + uni.getStorageSync("X-Token"),
							    },
                  formData:{zoom: 1},
							    name: 'file',
							    success(result) {
							      const data = JSON.parse(result.data);
							      if (data.code == 200) {
							        that.fileUrlList = [...that.fileUrlList, {attaId: data.data.attaId, attaName: data.data.attaName, attaPath: that.img_baseUrl + data.data.attaPath}];
							      } else {
							        uni.showToast({title: data.msg || '上传失败', icon: 'none'});
							      }
							    }
							  })
							})
						}
					})
				})
			},

			// 点击上传图片操作
			handleUploadVideo() {
				this.uploadVideo().then(res => {
					const urlList = this.videoUrlList;
					urlList.push(res);
					this.videoUrlList = urlList;
				})
			},
			//删除图片
			deleteVideo(src) {
				const imgArr = this.videoUrlList.filter(i => i != src);
				this.videoUrlList = imgArr;
			},
			// 上传方法
			uploadVideo() {
				return new Promise((resolve, reject) => {
					uni.chooseMedia({
						count: 1,
						sourceType: ['album', 'camera'],
						mediaType: ['video'],
						success(res) {
							if (res.tempFiles[0].size >= 5242880 * 20) {
								uni.showToast({
									title: '视频不能大于200M!',
									icon: 'none'
								})
								return
							} else {
								const tempFilePaths = res.tempFiles;
								uni.uploadFile({
									url: process.env.VUE_APP_BASEURL_API + "/file/uploadAttaData",
									header: {
										'Authorization': "Bearer " + uni.getStorageSync('X-Token')
									},
									filePath: tempFilePaths[0].tempFilePath,
									name: 'file',
									success(res) {
										const data = JSON.parse(res.data)
										console.log(data, "data")
										if (data.code == 200) {
											resolve(data.data)
										} else {
											uni.showToast(data.text);
											reject()
										}
									}
								})
							}
						}
					})
				})
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import "./editor.css";

	.my-container {
		position: relative;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #F7F9FA;


		.my-forms {
			width: 100%;
			height: calc(100vh - 188rpx);
			overflow: auto;
			background-color: #fff;
			padding: 30rpx 40rpx;
			border-bottom: 1rpx solid #E5E5E5;

			.my-list {

				.opt_1_view {
					display: flex;
					justify-content: flex-start;
					margin-bottom: 36rpx;

					.item {
						margin-right: 48rpx;

						.text {
							font-size: 28rpx;
							font-family: PingFang SC-Regular, PingFang SC;
							font-weight: 400;
							color: rgba(0, 0, 0, 0.7);
						}

						&.active {
							margin-right: 48rpx;
							position: relative;
							z-index: 0;

							.text {
								font-size: 32rpx;
								font-family: PingFang SC-Regular, PingFang SC;
								font-weight: 700;
								color: rgba(0, 0, 0, 0.7);
							}
						}
					}
				}


				.cell-column {
					display: flex;
					flex-direction: column;
					align-items: flex-start;
					justify-content: flex-start;
					height: auto;
					margin-bottom: 24rpx;

					.cell-text {
						width: 100%;
						font-size: 24rpx;
						font-weight: 400;
						color: rgba(0, 0, 0, 0.5);
						line-height: 32rpx;
						margin: 24rpx 0 0;
					}


					.imageList {
						width: 100%;
						height: auto;
						margin-top: 20rpx;
						background: #fff;
						display: flex;
						flex-direction: row;
						flex-wrap: wrap;
						align-items: flex-start;
						justify-content: flex-start;

						.image {
							width: 214rpx;
							height: 214rpx;
							// margin-right: 14rpx;
							// margin-bottom: 14rpx;
							border-radius: 24rpx;
							display: flex;
							justify-content: center;
							align-items: center;
							flex-direction: column;
							background: #F7F9FA;

							image {
								width: 72rpx;
								height: 72rpx;
							}

							text {
								font-size: 24rpx;
								font-family: Alibaba PuHuiTi 2.0-55 Regular, Alibaba PuHuiTi 20;
								font-weight: 400;
								color: #777F8F;
								margin-top: 12rpx;
							}
						}

						.imgItem {
							position: relative;
							width: 214rpx;
							height: 214rpx;
							margin-right: 14rpx;
							margin-bottom: 14rpx;

							.deleteImg {
								width: 48rpx;
								height: 48rpx;
								position: absolute;
								right: 12rpx;
								top: 12rpx;
							}

							.bofangImg {
								width: 72rpx !important;
								height: 72rpx !important;
								position: absolute;
								left: 50%;
								top: 50% !important;
								transform: translate(-50%, -50%);
							}

							&:nth-child(3n) {
								margin-right: 0rpx;
								// position: absolute;
								// right: 12rpx;
								// top: 12rpx;
								// height: 48rpx;
								// width: 48rpx;
							}

							video::-webkit-media-controls-start-playback-button {
								display: none;
							}
						}
					}
				}

				.cell-option {
					position: relative;
					width: 100%;
					height: 100%;
					flex: 1;

					.input {
						height: 120rpx;
						line-height: 120rpx;
						font-size: 40rpx;
						border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
						color: rgba(0, 0, 0, 0.3);
					}
				}

				.container {
					margin-top: 20rpx;

					.ql-container {
						box-sizing: border-box;
						padding: 12px 15px;
						width: 100%;
						min-height: 30vh;
						height: auto;
						background: #fff;
						font-size: 16px;
						line-height: 1.5;

					}

					.ql-active {
						color: #06c;
					}

					.iconfont {
						display: inline-block;
						padding: 8px 8px;
						width: 24px;
						height: 24px;
						cursor: pointer;
						font-size: 20px;
					}

					.toolbar {
						box-sizing: border-box;
						border-bottom: 0;
						font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
					}

				}
			}
		}


		.space {
			height: 24rpx;
			background-color: #F7F9FA;
		}

		.list {
			padding: 0 40rpx;

			.teacher_item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 28upx 0upx;
			}

			.list_center {
				flex: 1;
				padding: 0 24upx 0 20upx;
			}

			.list_left {
				display: flex;
				align-items: center;
			}

			.list_left image {
				width: 34upx;
				height: 34upx;
			}

			.list_name {
				font-size: 28upx;
				color: #000;
				font-weight: 700;
			}

			.list_right {
				width: 28rpx;
				height: 28rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}
		}

		.classification {
			padding: 24rpx 40rpx;

			.class_title {
				font-size: 28rpx;
				font-weight: 700;
				color: #3D3D3D;
				font-family: PingFang SC-Regular, PingFang SC;
				line-height: 40rpx;
				margin-bottom: 30rpx;
			}

			.class_list {
				display: flex;
				justify-content: flex-start;
				flex-wrap: wrap;

				.item {
					margin-right: 16rpx;
					padding: 8rpx 16rpx;
					border-radius: 8rpx;
					background-color: #F3F6F5;
					margin-bottom: 16rpx;

					.text {
						font-size: 28rpx;
						font-family: PingFang SC-Regular, PingFang SC;
						font-weight: 400;
						color: #5F6F86;
					}

					&.active_class {
						background-color: #3FAA73 ;

						.text {
							font-size: 28rpx;
							font-family: PingFang SC-Regular, PingFang SC;
							font-weight: 400;
							color: #fff;
						}
					}
				}
			}
		}

		.my-footer {
			position: fixed;
			bottom: 34rpx;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			width: 100%;
      background-color: white;
			.text {
				width: 686rpx;
				height: 88rpx;
        background: #3FAA73;
        border-radius: 44rpx 44rpx 44rpx 44rpx;
        margin: 20rpx 0;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
				font-weight: 400;
				color: #FFFFFF;
				line-height: 32rpx;
			}
		}
	}
</style>